const BaiduOCR = require('../../tool/ocr');
const ajax = require('../../tool/ajax');
const screen = require('../component/screen');//截图
let pupConfig, page, config, newUser;

/**
 * 注册页面脚本：检验图形验证码
 */
const start = async (myPupConfig) => {
  pupConfig = myPupConfig;
  page = pupConfig.page;
  config = pupConfig.config.common;
  newUser = pupConfig.config.newUser;

  await openRegister();
  await fillForm();
}

/**
 * 打开注册页
 */
const openRegister = async () => {
  //通过链接打开注册页
  await page.goto(config.host + 'register');
}

/**
 * 填写表单
 */
const fillForm = async () => {
  //等待页面加载完成
  await page.waitFor('input[type=text]');

  //获取输入框数组
  let inputs1 = await page.$$('input[type=text]');
  let inputs2 = await page.$$('input[type=password]');
  await inputs1[0].type(newUser.id);
  await inputs1[1].type(newUser.tel);
  await inputs1[2].type('1234');
  await inputs1[3].type('123456');
  await inputs2[0].type(newUser.password);
  await inputs2[1].type(newUser.password);

  //填写验证码并发送验证码
  await sendCode();

  //点击提交
  let button = await page.$('button[type=submit]');
  await button.click();

  await screen(page, '注册');
}

/**
 * 填写图形验证码
 */
const fillImageCode = async () => {
  let path = config.imgPath + '验证码.png';
  //输入框验证码
  let inputCode = await page.$('#imgValidCode');
  //图形验证码
  let imageCode = await page.$('img.picturecode-img');
  //保存验证码图片
  await imageCode.screenshot({path});
  //OCR识别验证码
  let result = await BaiduOCR.load(path).then((result) => {
    return result.words_result[0].words;
  });
  await inputCode.type(result);
}

/**
 * 填写图形验证码并发送验证码
 */
const sendCode = async () => {
  //是否发送成功
  let isSuccess = false;
  //图形验证码图片保存路径
  let path = config.imgPath + '验证码.png';
  //输入框验证码
  let inputCode = await page.$('#imgValidCode');
  //图形验证码
  let imageCode = await page.$('img.picturecode-img');
  //发送验证码按钮
  let btnCode = await page.$('.send-mobilecode-btn');
  while (!isSuccess) {
    //保存验证码图片
    await imageCode.screenshot({path});
    //OCR识别验证码
    let result = await BaiduOCR.load(path).then((result) => {
      if (result.words_result && result.words_result[0]) {
        return result.words_result[0].words;
      } else {
        return '1234';
      }
    });
    //输入图形验证码
    await inputCode.type(result);
    //点击发送验证码
    await btnCode.click();
    //发送验证码的结果
    let resultCode = await ajax.waitForResponse(page, 'sendSmsOtp.do');
    isSuccess = resultCode.code === '00000000';
    if (!isSuccess) {
      //等待获取图形验证码
      await ajax.waitForResponse(page, 'getImgValid.do');
    }
  }
}

module.exports = start;

